// pages/reviewRecord/readwork/readwork.js
const app = getApp();
const httpUtils = require('../../../utils/httpUtils.js');
let tool = require('../../../utils/tool.js');
const audio = require('../../../utils/audio.js');
//  正在录音的下标
let recordingIndex = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    readContent: {}, //阅读文章
    mainContent: "", //文章内容
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    hasreview: 0, //0未复习，1已提交复习
    hasRecord: 0, //0未录音，1有录音
    tempFilePaths: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/homework_img.png', //作业图片临时图片路径
    sort: '7',   //7做题拍照，8读一遍
    calendar_id: '',//任务id
    question_id: '',//文章id
    can_submit: 0, //1 可以提交 0不可以提交
    status: 0, //0未复习 1未完成 2已复习
    pic: "", //查看作业图片地址
    btnPlayStatus: [], //语音识别的三个按钮的状态
    uservoicetemp: "", //自己的录音上传后的路径
    voice: '',//自己录音的路径
    score: '-1',//语音识别的分数
    flag: true, //是否显示提交成功的弹窗
    showRecordModal: false, //正在识别的弹窗
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    if (options) {
      that.setData({
        calendar_id: options.calendar_id,
        question_id: options.question_id,
        sort: options.sort,
        can_submit: options.can_submit,
        status: options.status
      })
    }
    console.log("接收到的sort=" + that.data.sort + ", options.can_submit" + options.can_submit + ",status=" + options.status);
    that.getReadDetail();
  },

  //获取阅读复习详情
  getReadDetail() {
    var that = this;
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.getReadReviewDetail({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.calendar_id,
      question_id: that.data.question_id,
      type:that.data.sort
    }).then((res) => {
      console.log(res)
      let readcontent = res.data.content;
      readcontent = readcontent.replace(/#/g, "_");
      readcontent = readcontent.replace(/\n/g, "\n　");
      that.setData({
        readContent: res.data,
        mainContent: readcontent,
        pic: res.data.pic,
        voice: res.data.voice,
        score: res.data.score
      })

      if (that.data.sort == 8) {
        //如果有读一遍，初始化一下audio
        let len = 1;
        that.setData({
          btnPlayStatus: audio.initAudioBtn(len, len)
        })
        audio.onEnded({
          callback(data) {
            that.setData({
              btnPlayStatus: data
            })
          }
        });
      }

    });
  },

  // 点击选择图片
  selectPicture() {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempsrc = res.tempFilePaths[0];
        console.log("临时文件地址:", tempsrc);
        that.setData({
          tempFilePaths: tempsrc,
        })
        //上传图片
        that.uploadPic();
      },
    })
  },

  /**
   * 上传图片到服务器
   */
  uploadPic: function () {
    let that = this;
    wx.showLoading({
      title: '正在上传',
      mask: true
    })
    let bodyParam = {
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      type: that.data.tempFilePaths,
    }
    let rs = tool.getSign(bodyParam, getApp().globalData.key);
    let tempurl = getApp().globalData.apiURL + 'common/upload?sign=' + rs.sign;
    console.log(tempurl)
    wx.uploadFile({
      url: tempurl,
      filePath: that.data.tempFilePaths,
      name: 'file',
      formData: {
        'type': that.data.tempFilePaths,
      },
      success(res) {
        wx.hideLoading();
        console.log("res.data=" + res.data)
        let str = res.data.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
        let result = JSON.parse(str);
        let path = result.data.path;
        console.log(path)

        that.setData({
          picturepath: path,
        })

        wx.showToast({
          title: '图片上传成功',
          icon: 'none',
          duration: 1000
        })
      },

    })

  },


  //  录音并打分
  recordScore: function (event) {
    var that = this;
    audio.stop({
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });

    that.setData({
      showRecordModal: true,
      originalStr: that.data.readContent.content
    });
    console.log("originalStr:" + that.data.originalStr)
  },

  //录音失败
  recordFail:function(res){
  let that =this;
  if(that.data.showRecordModal){
    that.setData({
      showRecordModal: false,
    });
    console.log("readwork界面recordFail,设置弹窗false")
  }
  },

  // 录音成功
  recordSuccess: function (res) {
    let that = this;
    console.log("录音成功" + JSON.stringify(res))
    if(that.data.showRecordModal){
      that.setData({
        showRecordModal: false,
      });
    }

    let score = res.detail.score;
    console.log("score=" + score)
    let tempFilePath = res.detail.tempFilePath;
    if (score < 0) {
      wx.showToast({
        title: '没有听清~',
        icon: 'none',
        duration: 2000
      });
    } else {
      that.setData({
        voice: tempFilePath,
        score: score
      })

      let bodyParam = {
        access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
        type: tempFilePath,
      }
      let rs = tool.getSign(bodyParam, getApp().globalData.key);
      let tempurl = getApp().globalData.apiURL + 'common/upload?sign=' + rs.sign;
      console.log(tempurl)
      wx.uploadFile({
        url: tempurl,
        filePath: tempFilePath,
        name: 'file',
        formData: {
          'word': that.data.question_id,
          'sub_vedio': tempFilePath,
          'type': 'wx_voice',
        },
        success(res) {
          console.log("录音上传成功")
          let result = JSON.parse(res.data);
          let path = result.data.path;
          console.log(path)
          that.setData({
            uservoicetemp: path
          })
        },
      })
    }
  },


  //播放录音
  playAudio(event) {
    var that = this;
    var type = event.currentTarget.dataset.type;
    var index = event.currentTarget.dataset.index;
    console.log("type=" + type + ",index=" + index)

    audio.play({
      type: type,
      index: index,
      audiosrc: event.currentTarget.dataset.audiosrc,
      callback(data) {
        that.setData({
          btnPlayStatus: data,
        });
      }
    });
  },

  //提交复习
  submitReview() {
    let that = this;
    let picurl = that.data.picturepath;
    if (that.data.sort == 7 && !that.data.picturepath) {
      wx.showToast({
        title: '请先上传作业图片',
        icon: 'none',
        duration: 1000
      })
      return;
    } else if (that.data.sort == 8) {
      picurl = ""
      if(that.data.showRecordModal){
        console.log("正在录音")
       return;
      }
      if (that.data.score < 0) {
        wx.showToast({
          title: '请先录音后再提交',
          icon: 'none',
          duration: 1000
        })
        return;
      }
    }

    wx.showModal({
      title: '提示',
      content: '是否确定提交',
      success(res) {
        if (res.confirm) {
          that.setData({
            showRecordModal:false
          })
          that.submitAnswer(picurl);
        } else if (res.cancel) {
          console.log("点击了取消") 
        }
      }
    })
   
  },

  submitAnswer(picurl){
    let that = this;
    wx.showLoading({
      title: '正在提交',
      mask: true
    })
    httpUtils.submitRWReview({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      calendar_id: that.data.calendar_id,
      id: that.data.readContent.id,
      question_type: 1,  //1 阅读 4 写作
      sort: that.data.sort,
      pic: picurl, //拍照图片地址
      voice: that.data.uservoicetemp,//录音文件地址
      score: that.data.score, //语音识别的分数
    }).then((res) => {
      wx.hideLoading();
      that.setData({
        flag: false
      })
      // wx.showToast({
      //   title: '作业提交成功~',
      //   icon: 'success',
      //   duration: 1000
      // })

  
    });
  },
  //点击弹窗中的完成按钮
  goComplet() {
    wx.navigateBack({
      delta: -1
    })
  },

  //点击查看大图
  lookBigPic() {
    let that = this;
    //修改本句的imgurl为上次上传的图片地址即可
    // let imgUrl = that.data.imitation.pic;
    let imgUrl = that.data.pic;
    //在新界面预览样例大图
    wx.previewImage({
      current: imgUrl,
      urls: [imgUrl],
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this;
    audio.destory();
    console.log("readwork界面onHide")
    // that.setData({
    //   showRecordModal:false
    // })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that =this;
    audio.destory();
    that.setData({
      showRecordModal:false
    })
  },

  

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})